﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using NetComm;

namespace Host
{
    public partial class MainDisplay : Form
    {
        public MainDisplay()
        {
            InitializeComponent();
        }

        NetComm.Host Server;
        List<string> Clients = new List<string>();

        private void MainDisplay_Load(object sender, EventArgs e)
        {
            Server = new NetComm.Host(2020); //Initialize the Server object, connection will use the 2020 port number
            Server.StartConnection(); //Starts listening for incoming clients

            //Adding event handling methods, to handle the server messages
            Server.onConnection += new NetComm.Host.onConnectionEventHandler(Server_onConnection);
            Server.lostConnection += new NetComm.Host.lostConnectionEventHandler(Server_lostConnection);
            Server.DataReceived += new NetComm.Host.DataReceivedEventHandler(Server_DataReceived);
        }

        private void MainDisplay_FormClosing(object sender, FormClosingEventArgs e)
        {
            Server.CloseConnection(); //Closes all of the opened connections and stops listening
        }

        void Server_DataReceived(string ID, byte[] Data)
        {
            string d = ConvertBytesToString(Data);

            Log.AppendText(d + Environment.NewLine);
            string[] lines = d.Split('|');

            string from = lines[0].Replace("from:", "");
            string to = lines[1].Replace("to:", "");
            string cmd = lines[2].Replace("cmd:", "");
            string param = lines[3].Replace("param:", "");

            //if (to == "broadcast")
            //{
            //    Server.Brodcast(Data);
            //}

            //Server.SendData(to, Data);
        }
       

        void Server_onConnection(string id)
        {
            Clients.Add(id);
            lb_clients.Items.Add(id);

            string clientsrow = "";
            foreach (string item in Clients)
            {
                clientsrow += item + ",";
            }
            clientsrow = clientsrow.Remove(clientsrow.Length - 1);

            foreach(string item in Clients)
            {
                string msg = "";

                // ha új, egész kliens listát küldünk neki
                if (item == id)
                {
                    msg += "from:server";
                    msg += "|";
                    msg += "to:" + item;
                    msg += "|";
                    msg += "cmd:" + "addclientlist";
                    msg += "|";
                    msg += "param:" + clientsrow;
                }
                // ha régi, csak az belépő tag ID-t kapja
                else
                {
                    msg += "from:server";
                    msg += "|";
                    msg += "to:" + item;
                    msg += "|";
                    msg += "cmd:" + "addclient";
                    msg += "|";
                    msg += "param:" + id;
                }

                Server.SendData(item, StringToByteArray(msg));
            }


            Log.AppendText(DateTime.Now + " - " + id + " connected!" + Environment.NewLine); //Updates the log textbox when new user joined
        }

        void Server_lostConnection(string id)
        {
            if (Clients.Contains(id))
                Clients.Remove(id);
            
            lb_clients.Items.Remove(id);

            foreach (string item in Clients)
            {
                string msg = "";

                msg += "from:server";
                msg += "|";
                msg += "to:" + item;
                msg += "|";
                msg += "cmd:" + "delclient";
                msg += "|";
                msg += "param:" + id;
                
                Server.SendData(item, StringToByteArray(msg));
            }
            
            if (Log.IsDisposed) return; //Fixes the invoke error
            Log.AppendText(DateTime.Now + " - " + id + " disconnected" + Environment.NewLine); //Updates the log textbox when user leaves the room
        }

        

        string ConvertBytesToString(byte[] bytes)
        {
            return ASCIIEncoding.ASCII.GetString(bytes);
        }

        public static byte[] StringToByteArray(string str)
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            return encoding.GetBytes(str);
        }

        public static string BytesToString(byte[] dBytes)
        {            
            string str;
            System.Text.UTF8Encoding enc = new System.Text.UTF8Encoding();
            str = enc.GetString(dBytes);

            return str;
        }
    }
}
